import axios from 'axios'
import {
    Message,
    Notification
} from 'element-ui'
import Vue from 'vue'
import Router from 'vue-router'
import router from '../router'
import store from '../store/index'

Vue.use(Router)
const originalPush = Router.prototype.push
Router.prototype.push = function push(location) {
    return originalPush.call(this, location).catch(err => err)
}

const iscUrl = 'http://localhost:3000/admin/api'
// const iscUrl = window.appConfig.apiIscUrl
// const supportUrl = window.appConfig.apiSupportUrl
const supportUrl ='http://localhost:3000/admin/api'
// const authUrl = window.appConfig.apiAuthUrl
const authUrl ='http://localhost:3000/admin/api'
const header = {
        'Access-Control-Allow-Origin': '*',
        'Access-Control-Allow-Methods': 'OPTIONS,HEAD,GET,PUT,POST,DELETE,PATCH'
    }
    // 文件上传
const headers2 = {
        'enctype': 'multipart/form-data'
    }
    // 图片预览
const headers3 = {
    'Access-Control-Allow-Origin': '*',
    'Content-Type': 'application/octet-stream'
}

const postHeader = Object.assign({}, header, {
    'Content-Type': 'application/json;charset=UTF-8'
})

export function setToken() {
    // 供应商端添加token
    const baseUrl ='http:localhost:8080/admin/api';
    // const baseUrl = window.appConfig.baseUrl;
    // Authorization
    if (baseUrl === '/supplier') {
        let token = JSON.parse(localStorage.getItem('userInfo')) && JSON.parse(localStorage.getItem('userInfo')).token
        header.Authorization = token
        headers2.Authorization = token
        headers3.Authorization = token
        postHeader.Authorization = token
    }
}

setToken()

const CancelToken = axios.CancelToken
let source = CancelToken.source()

let cancel = null
let promiseArr = {}

const No_loading_url = [
    '/giraffe/api/supplier/manage/todoList', // todo列表
    '/giraffe/api/supplier/manage/dropDown/org/list', // org列表
    '/giraffe/api/supplier/manage/companyApi/page', // 公司列表
    '/giraffe/api/supplier/manage/dropDown/audit/list', // 审核org列表
    '/giraffe/api/supplier/manage/dropDown/enum/all', // 下拉列表

    '/giraffe/api/supplier/manage/unLoginApi/announcementPage', //登录页通知公告
    '/giraffe/api/supplier/manage/unLoginApi/query', // 友情链接

    '/giraffe/api/supplier/center/todoList', // tode列表
    '/giraffe/api/supplier/center/dropDown/enum/all', // 下拉列表
]

axios.interceptors.request.use(config => {
    // 添加 loading 动画
    if (`${No_loading_url.indexOf(config.url)}` === '-1') {
        store.dispatch('sup/showLoading')
    }
    // 取消当前正在进行的相同请求
    if (promiseArr[config.url]) {
        promiseArr[config.url]('操作取消')
        promiseArr[config.url] = cancel
    } else {
        promiseArr[config.url] = cancel
    }
    if (!config.headers.hasOwnProperty('Authorizatio-n')) {
        config.headers['Authorizatio-n'] = sessionStorage.getItem('jwt')
    }
    config.cancelToken = source.token // 全局添加cancelToken
    return config
}, error => {
    store.dispatch('sup/hiddenLoading')
    Message.error({
        message: '加载超时'
    })
    return Promise.reject(error.request)
})

// http响应拦截器
axios.interceptors.response.use(response => {
    // 取消 loading 动画
    const config = response.config
    if (`${No_loading_url.indexOf(config.url)}` === '-1') {
        store.dispatch('sup/hiddenLoading')
    }
    // 无权限
    if (response.data.message === 'current user has no permission') {
        source.cancel() // 取消其他正在进行的请求
        router.push('/unauthorized')
        source = CancelToken.source()
    } else {}
    if (response.data.code == 402) {
        Notification({
            title: '提示',
            message: '当前为默认密码，为了你的账号安全，请及时修改密码',
            duration: 8000,
            offset: 55
        });
    }
    // 登录失效401
    if (response.data.code == 401 || response.status == 401 || response.code == 401) {
        // Message.error({message: response.data.message})
        source.cancel() // 取消其他正在进行的请求
            // let count = localStorage.getItem('count401')
            // if (!count && !response.config.url.includes('curuser')) {
            // localStorage.setItem('count401', '0')
        localStorage.removeItem('user')
        localStorage.removeItem('menus')
        localStorage.removeItem('userInfo')
        router.push('/login')
        source = CancelToken.source()
            // } else {
            // localStorage.setItem('count401', (Number(localStorage.getItem('count401')) + 1).toString())
            // }
    }
    return response
}, error => {
    store.dispatch('sup/hiddenLoading')
    errorHandler(error)
    if (error.message !== '操作取消') {
        if (error.message) {
            Message.error({
                message: error.msg
            })
        }
    }
    return Promise.reject(error.response)
})

// 移除拦截器
// axios.interceptors.request.eject('拦截器名称')

function checkStatus(response) {
    if (response && (response.status === 200 || response.status === 304 || response.status === 400)) {
        return response.data
    }
    return {
        success: false,
        status: -404,
        message: '网络异常'
    }
}

function checkCode(res) {
    // if (!res.success) {
    //   Message.error({
    //     message: res.message
    //   })
    // }
    if (res.status === -404) {
        Message.error({
            message: res.message
        })
    }
    return res
}

function errorHandler(error) {
    if (error && error.response) {
        switch (error.response.status) {
            case 400:
                error.msg = '错误请求';
                break
            case 401:
                error.msg = '未授权，请重新登录';
                break
            case 403:
                error.msg = '拒绝访问';
                break
            case 404:
                error.msg = '请求错误，未找到该资源';
                break
            case 405:
                error.msg = '请求方法未允许';
                break
            case 408:
                error.msg = '请求超时';
                break
            case 500:
                error.msg = '服务器端出错';
                break
            case 501:
                error.msg = '网络未实现';
                break
            case 502:
                error.msg = '网络错误';
                break
            case 503:
                error.msg = '服务不可用';
                break
            case 504:
                error.msg = '网络超时';
                break
            case 505:
                error.msg = 'http版本不支持该请求';
                break
            default:
                error.msg = `连接错误${error.response.status}`
        }
    } else {
        error.msg = '连接到服务器失败'
    }
    console.log(error.msg)
}

/**
 * header请求参数添加和替换
 * @param params 请求参数
 * @param replaceName 需要替换的字段
 */

// 判断接口是否需要二次校验
export const isNeedCheck = (type, url) => {
    if (!sessionStorage.getItem('checkList')) return false
    const checkList = JSON.parse(sessionStorage.getItem('checkList'))
    if (checkList && checkList[type]) {
        for (let index = 0; index < checkList[type].length; index++) {
            const str = `^${checkList[type][index]}(\\w*|\\?.*)$`
            const reg = new RegExp(str)
            if (reg.test(url)) {
                return true
            }
        }
    }
    return false
}

export default {
    iscGet(url, params, checkMark, checked) {
        // eslint-disable-next-line no-unused-expressions
        checked ? (postHeader['checkMark'] = checkMark['checkMark']) : ''
        return axios({
            method: 'get',
            url: iscUrl + url,
            params,
            timeout: 90000,
            headers: header
                // cancelToken: new CancelToken(c => {
                //   cancel = c
                // })
        }).then(response => {
            return checkStatus(response)
        }).then(res => {
            return checkCode(res)
        })
    },
    iscGet2(url, params, checkMark, checked) {
        // eslint-disable-next-line no-unused-expressions
        checked ? (postHeader['checkMark'] = checkMark['checkMark']) : ''
        return axios({
            method: 'get',
            url: iscUrl + url,
            data: params,
            timeout: 90000,
            headers: header
                // cancelToken: new CancelToken(c => {
                //   cancel = c
                // })
        }).then(response => {
            return checkStatus(response)
        }).then(res => {
            return checkCode(res)
        })
    },
    iscPost(url, options, checkMark, checked) {
        if (!checked && isNeedCheck('post', url)) {
            return new Promise((resolve, reject) => {
                resolve({
                    needCheck: true,
                    requestParam: {
                        type: 'post',
                        url,
                        options
                    }
                })
            })
        }
        // eslint-disable-next-line no-unused-expressions
        checked ? (postHeader['checkMark'] = checkMark['checkMark']) : ''
        return axios({
            method: 'post',
            url: iscUrl + url,
            data: options,
            timeout: 90000,
            headers: postHeader
        }).then(response => {
            return checkStatus(response)
        }).then(res => {
            return checkCode(res)
        })
    },
    iscDelete(url, params, checkMark, checked, jsonP) {
        if (!checked && isNeedCheck('delete', url)) {
            return new Promise((resolve, reject) => {
                resolve({
                    needCheck: true,
                    requestParam: {
                        type: 'delete',
                        url,
                        params
                    }
                })
            })
        }
        // eslint-disable-next-line no-unused-expressions
        checked ? (header['checkMark'] = checkMark['checkMark']) : ''
        const deleteHeader = jsonP ? postHeader : header
        return axios({
            method: 'delete',
            url: iscUrl + url,
            params: jsonP ? '' : params,
            data: jsonP ? params : '',
            timeout: 90000,
            headers: deleteHeader
        }).then(response => {
            return checkStatus(response)
        }).then(res => {
            return checkCode(res)
        })
    },
    iscPut(url, options, checkMark, checked) {
        if (!checked && isNeedCheck('put', url)) {
            return new Promise((resolve, reject) => {
                resolve({
                    needCheck: true,
                    requestParam: {
                        type: 'put',
                        url,
                        options
                    }
                })
            })
        }
        // eslint-disable-next-line no-unused-expressions
        checked ? (postHeader['checkMark'] = checkMark['checkMark']) : ''
        return axios({
            method: 'put',
            url: iscUrl + url,
            data: options,
            timeout: 90000,
            headers: postHeader
        }).then(response => {
            return checkStatus(response)
        }).then(res => {
            return checkCode(res)
        })
    },
    iscPatch(url, options, checkMark, checked) {
        if (!checked && isNeedCheck('patch', url)) {
            return new Promise((resolve, reject) => {
                resolve({
                    needCheck: true,
                    requestParam: {
                        type: 'patch',
                        url,
                        options
                    }
                })
            })
        }
        // eslint-disable-next-line no-unused-expressions
        checked ? (postHeader['checkMark'] = checkMark['checkMark']) : ''
        return axios({
            method: 'patch',
            url: iscUrl + url,
            data: options,
            timeout: 90000,
            headers: postHeader
        }).then(response => {
            return checkStatus(response)
        }).then(res => {
            return checkCode(res)
        })
    },
    authPost(url, options, checkMark, checked) {
        if (!checked && isNeedCheck('post', url)) {
            return new Promise((resolve, reject) => {
                resolve({
                    needCheck: true,
                    requestParam: {
                        type: 'post',
                        url,
                        options
                    }
                })
            })
        }
        // eslint-disable-next-line no-unused-expressions
        checked ? (postHeader['checkMark'] = checkMark['checkMark']) : ''
        return axios({
            method: 'post',
            url: authUrl + url,
            data: options,
            timeout: 90000,
            headers: postHeader
        }).then(response => {
            return checkStatus(response)
        }).then(res => {
            return checkCode(res)
        })
    },
    authGet(url, options, checkMark, checked) {
        if (!checked && isNeedCheck('get', url)) {
            return new Promise((resolve, reject) => {
                resolve({
                    needCheck: true,
                    requestParam: {
                        type: 'get',
                        url,
                        options
                    }
                })
            })
        }
        // eslint-disable-next-line no-unused-expressions
        checked ? (postHeader['checkMark'] = checkMark['checkMark']) : ''
        return axios({
            method: 'get',
            url: authUrl + url,
            data: options,
            timeout: 90000,
            headers: postHeader
        }).then(response => {
            return checkStatus(response)
        }).then(res => {
            return checkCode(res)
        })
    },
    supportGet(url, params) {
        return axios({
            method: 'get',
            url: supportUrl + url,
            params,
            timeout: 90000,
            headers: header
                // cancelToken: new CancelToken(c => {
                //   cancel = c
                // })
        }).then(response => {
            return checkStatus(response)
        }).then(res => {
            return checkCode(res)
        })
    },
    supportPost(url, options) {
        return axios({
            method: 'post',
            url: supportUrl + url,
            data: options,
            timeout: 90000,
            headers: postHeader
        }).then(response => {
            return checkStatus(response)
        }).then(res => {
            return checkCode(res)
        })
    },
    supportPost_params(url, options) {
        return axios({
            method: 'post',
            url: supportUrl + url,
            params: options,
            timeout: 90000,
            headers: postHeader
        }).then(response => {
            return checkStatus(response)
        }).then(res => {
            return checkCode(res)
        })
    },
    supportLongGet(url, params) {
        return axios({
            method: 'get',
            url: supportUrl + url,
            params,
            timeout: 90000,
            headers: header
                // cancelToken: new CancelToken(c => {
                //   cancel = c
                // })
        }).then(response => {
            return checkStatus(response)
        }).then(res => {
            return checkCode(res)
        })
    },
    supportLongPost(url, options) {
        return axios({
            method: 'post',
            url: supportUrl + url,
            data: options,
            timeout: 90000,
            headers: postHeader
        }).then(response => {
            return checkStatus(response)
        }).then(res => {
            return checkCode(res)
        })
    },
    supportDelete(url, params) {
        return axios({
            method: 'delete',
            url: supportUrl + url,
            params,
            timeout: 90000,
            headers: header
        }).then(response => {
            return checkStatus(response)
        }).then(res => {
            return checkCode(res)
        })
    },
    supportDelete_data(url, params) {
        return axios({
            method: 'delete',
            url: supportUrl + url,
            data: params,
            timeout: 90000,
            headers: header
        }).then(response => {
            return checkStatus(response)
        }).then(res => {
            return checkCode(res)
        })
    },
    supportPut(url, options) {
        return axios({
            method: 'put',
            url: supportUrl + url,
            data: options,
            timeout: 90000,
            headers: postHeader
        }).then(response => {
            return checkStatus(response)
        }).then(res => {
            return checkCode(res)
        })
    },
    supportPutParams(url, options) {
        return axios({
            method: 'put',
            url: supportUrl + url,
            params: options,
            timeout: 90000,
            headers: postHeader
        }).then(response => {
            return checkStatus(response)
        }).then(res => {
            return checkCode(res)
        })
    },
    supportPatch(url, options) {
        return axios({
            method: 'patch',
            url: supportUrl + url,
            data: options,
            timeout: 90000,
            headers: postHeader
        }).then(response => {
            return checkStatus(response)
        }).then(res => {
            return checkCode(res)
        })
    },
    // 文件上传
    uploadFile(url, options) {
        return axios({
            method: 'post',
            url: supportUrl + url,
            data: options,
            timeout: 90000,
            headers: headers2
        }).then(response => {
            return checkStatus(response)
        }).then(res => {
            return checkCode(res)
        })
    },
    // 预览文件的请求
    imagePreview(url, params) {
        return axios({
            method: 'get',
            url: supportUrl + url,
            data: params,
            timeout: 90000,
            headers: headers3
        }).then(response => {
            return checkStatus(response)
        }).then(res => {
            return checkCode(res)
        })
    }
}